package com.hnao.serialport

import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.KeyEvent
import com.hnao.serialport.utils.ScanKeyEventHelper
import java.math.BigInteger

/**
 * @Author caow
 * 2025/2/19
 */
object SerialPortScanKeyManager {
    private val mScanKeyEventHelper: ScanKeyEventHelper = ScanKeyEventHelper { barcode ->
        Log.i("caow", "${barcode.length}: $barcode")
        try {
            val cardId = BigInteger(barcode, 16)
            val card = cardId.toString(10)

            Log.i("caow", "cardId: $cardId")
            Log.i("caow", "card: $card")

            val message = Message.obtain()
            message.what = 1
            message.obj = card
            handler.sendMessage(message)

        } catch (e: Exception) {
            e.printStackTrace()
            val message = Message.obtain()
            message.what = 1
            message.obj = barcode
            handler.sendMessage(message)
        }
    }

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                val result = msg.obj as String
                Log.i("caow", "handleMessage: $result")
                SerialPortCallbackListener.listener?.invoke(result)
            }
        }
    }

    fun dispatchKeyEvent(event: KeyEvent?): Boolean? {
//        ZLog.i(event.toString());
        if (event?.deviceId != -1) {
            mScanKeyEventHelper.analysisKeyEvent(event)
            return true
        }
        return null
    }
}